import { Fragment, useEffect, useRef, useState } from "react";
import lessModule from "./index.module.less";
import { Button, Input, Select } from "antd";
import HomePage_SingleBtnComponent from "../../../singleBtn";
import HomePage_ModalComponent from "../../../modal";
import HomePage_DateTimePickerRangeComponent from "../../../dateTimePickerRange";
import searchImage from "../../../../../../assets/image/homePage-search.png"
import HomePage_HeaderOperationComponent_LayoutSettingComponent from "../layoutSetting";
import { $eventBus, $EventBus_off, $EventBus_on } from "../../../../../../common/utils";
import HomePage_MultipleBtnComponent from "../../../multipleBtn";

// 主页-头部操作组件-条件组件
interface homePageHeaderOperationComponentConditionComponentComponentInterface {
  sourceData: object
}

const HomePage_HeaderOperationComponentConditionComponent: React.FC<homePageHeaderOperationComponentConditionComponentComponentInterface> = (props) => {
  const [paramsData, setParamsData] = useState<object>({ ...props.sourceData?.["initParamsData"] })
  const isInit = useRef<boolean>(true)
  const antiShakeKey = useRef<string>("")
  const [selectedValue, setSelectedValue] = useState<string>("")
  const change_select = (key: string, value: string) => {
    paramsData[key] = value
    if (key === "monitoringType" && "deviceID" in paramsData) {      
      paramsData["deviceID"] = ""
      setSelectedValue("")
    }
    setParamsData({ ...paramsData })
    emit_paramsData()
  }

  const change_input = (key: string, value: string) => {
    antiShakeKey.current = key
    paramsData[key] = value
    setParamsData({ ...paramsData })
  }

  const emit_paramsData = () => {
    setTimeout(() => {
      $eventBus.emit("headerOperationSearch", { source: "HomePage_HeaderOperationComponentConditionComponent", explain: "数据已更新，请按需执行头部操作查询", data: { paramsData } })
    });
  }

  const change_rangePicker = (keyList: Array<string>, dateStringList: Array<string>) => {
    paramsData[keyList[0]] = dateStringList[0]
    paramsData[keyList[1]] = dateStringList[1]
    setParamsData({ ...paramsData })
    emit_paramsData()
  }

  const change_multipleBtnSelectedList = (list: Array<string>) => {
    paramsData[props.sourceData["multipleBtnKey"]] = list
    setParamsData({ ...paramsData })
    emit_paramsData()
  }
  // 广播函数数据
  const eventBusFuncData = {
    selectMonitorModalSelectedList: (data) => {

      if (data["data"]["mode"] === "single") {
        if (paramsData[props.sourceData["singleBtnKey"]] !== data["data"]["selectedList"][0]) {
          if (props.sourceData["singleBtnValueKey"]) {

            paramsData[props.sourceData["singleBtnKey"]] = data["data"]["selectedOtherList"][0][props.sourceData["singleBtnValueKey"]]
          } else {
            paramsData[props.sourceData["singleBtnKey"]] = data["data"]["selectedList"][0]
          }
          setSelectedValue(data["data"]["selectedList"][0])
          setParamsData({ ...paramsData })
          emit_paramsData()
        }


      } else if (data["data"]["mode"] === "multiple") {
        if (paramsData[props.sourceData["multipleBtnKey"]] !== data["data"]["selectedList"]) {
          paramsData[props.sourceData["multipleBtnKey"]] = data["data"]["selectedList"]
          setParamsData({ ...paramsData })
          emit_paramsData()
        }

      }

    },
    homePageTagComponentDel: (data) => {
      paramsData[props.sourceData["multipleBtnKey"]] = data
      setParamsData({ ...paramsData })
      emit_paramsData()
    }
  }
  // 搜索框防抖
  useEffect(() => {
    const antiShakeTimeout = setTimeout(() => {
      !isInit.current && emit_paramsData()
      isInit.current = false
    }, 300);
    return () => {
      clearTimeout(antiShakeTimeout);
    };
  }, [paramsData[antiShakeKey.current]])


  useEffect(() => {
    $EventBus_on(eventBusFuncData)
    return () => {
      $EventBus_off(eventBusFuncData)
    }
  }, [])
  return (
    <div className={lessModule["homePageHeaderOperationComponentConditionComponent"]}>
      {
        props.sourceData?.["conditionList"]?.map((item, idx) => (
          <Fragment key={`conditionItem${idx}`} >
            {

              !((item["type"] === "singleBtn" || item["type"] === "multipleBtn") && paramsData["monitoringType"] === "全部") && <div className={lessModule["homePageHeaderOperationComponentConditionComponent-group"]}>
                <span>{item["label"]}：</span>
                {
                  item["type"] === "select" &&
                  <Select showSearch
                    style={{ minWidth: 120 }}
                    placeholder="请选择"
                    value={paramsData[item["key"]]}
                    options={item["optionList"]}
                    onChange={(value: string) => change_select(item["key"], value)}
                    fieldNames={{ value: "label" }}
                  />
                }
                {
                  item["type"] === "singleBtn" && paramsData["monitoringType"] !== "全部" && <HomePage_SingleBtnComponent operation={props.sourceData?.["selectMonitorOperation"]} selectedValue={selectedValue} minWidth={120} monitoringType={item["monitoringType"] || paramsData["monitoringType"]} monitorModalName={item["monitorModalName"]} />
                }
                {
                  item["type"] === "multipleBtn" && paramsData["monitoringType"] !== "全部" && <HomePage_MultipleBtnComponent selectedList={paramsData[props.sourceData["multipleBtnKey"]]} minWidth={120} monitoringType={item["monitoringType"] || paramsData["monitoringType"]} monitorModalName={item["monitorModalName"]} change_selectedList={change_multipleBtnSelectedList} />
                }
                {
                  item["type"] === "dateTimePickerRange" && <HomePage_DateTimePickerRangeComponent isHideInit width={330} change_rangePicker={(dateStringList: Array<string>) => change_rangePicker(item["keyList"], dateStringList)} />
                }
                {
                  item["type"] === "input" && <Input style={{ width: item["width"] }} placeholder="请输入" onChange={(e) => change_input(item["key"], e["target"]["value"])} />
                }
              </div>
            }
          </Fragment>
        ))
      }

    </div>
  )
}



export default HomePage_HeaderOperationComponentConditionComponent
